package com.wust.weibo;
/**
 * @author tianzhihen
 * @version create time：2012-7-18 下午5:00:32
 * 类说明
 */

import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Pattern;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;




import com.wust.baby.picture.ImageSwitcherAndGalleryDemoActivity;
import com.wust.footprint.FirstActivity;
import com.wust.loveangel.loveAngelActivity2;
import com.wust.menu.FirstGroupTab;
import com.wust.menu.FourthGroupTab;
import com.wust.menu.ThirdGroupTab;
import com.wust.util.*;

import com.wust.R;

import com.wust.user.User;
import com.wust.weibo.AsyncImageLoader.ImageCallback;
import com.wust.weibo.WeiBoType.PageType;



import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableString;
import android.util.Log;
import android.view.*;
import android.view.View.OnClickListener;

import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.*;

public class HomeActivity extends Activity implements OnItemClickListener,OnItemLongClickListener,OnScrollListener{
	
	private ListView listView;
	private HomeAdapter adapter;
	private JSONArray array;
	private AsyncImageLoader asyncImageLoader;
	private Handler handler;
	private ProgressDialog progressDialog;
	private View top_panel;
	private Button top_btn_left;
	private Button top_btn_right;
	private TextView top_title;
//	private LinearLayout list_footer;
//	private TextView tv_msg;
//	private LinearLayout loading;
	private List<JSONObject> list;//微博数据列表
	private ExecutorService executorService;
	private static int PAGE_SIZE = 20;//每页显示的微博条数
	private int TOTAL_PAGE = 0;//当前已经记在的微博页数

	WeiBoAPI client=new WeiBoAPI();   //与服务器端交互的
	
	private static int THREADPOOL_SIZE = 7;//线程池的大小
	
	
	
	/**********************************/
	 private LinearLayout.LayoutParams mLayoutParams =new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
     private LinearLayout. LayoutParams FFlayoutParams = new LinearLayout.LayoutParams(  LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);
     private ProgressBar progressBar;
     LinearLayout loadingLayout;
     private Thread mThread;
     private Handler loadinghandler =new Handler()
     {
    	 public void handleMessage(Message msg)
    	 {
    		 switch(msg.what)
    		 {
    		 case 1:
    			 if(true) //无限的加载下去  当然这样无限下去肯定是有问题的，缓存到底能装多少   那么将腾讯的微博那么无限的点下去是不是会无限的出现呢
    			 {
    				 
    				 Toast.makeText(getApplicationContext(), "这是数据的第"+adapter.getCount()/10+"页", 1).show();
    			 }
    			 else listView.removeFooterView(loadingLayout);
    			 adapter.notifyDataSetChanged();
    			 break;
    			default:break;
    		 }
    	 }
    	 
     };
	
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home);
		setUpViews();
		setUpListeners();
		
		/****************************************************后来添加*/
		initFootView();
		
		progressDialog = new ProgressDialog(HomeActivity.this.getParent());// 生成一个进度条
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progressDialog.setTitle("请稍等");
		progressDialog.setMessage("正在读取数据中!");
	 	handler = new GetHomeTimeLineHandler();
		

		
		executorService.submit(new GetHomeTimeLineThread());//耗时操作,开启一个新线程获取数据
		Toast.makeText(getApplicationContext(), "正在抓捕其众父母的心情", 1).show();
		progressDialog.show();
	}
	
	private void setUpViews(){
	//	list_footer = (LinearLayout)LayoutInflater.from(HomeActivity.this).inflate(R.layout.list_footer, null);
	//	tv_msg = (TextView)list_footer.findViewById(R.id.tv_msg);
		//loading = (LinearLayout)list_footer.findViewById(R.id.loading);
		listView = (ListView) this.findViewById(R.id.weibo_list);//getListView();
		top_panel = (View)findViewById(R.id.home_top);
		top_btn_left = (Button)top_panel.findViewById(R.id.top_btn_left);
		top_btn_right = (Button)top_panel.findViewById(R.id.top_btn_right);
		top_title = (TextView)top_panel.findViewById(R.id.top_title);
	//	listView.addFooterView(list_footer);//这儿是关键中的关键呀，利用FooterVIew分页动态加载
		list = new ArrayList<JSONObject>();
	//	executorService = Executors.newCachedThreadPool();
		executorService = Executors.newFixedThreadPool(THREADPOOL_SIZE);
	}
	
	private void setUpListeners(){
		listView.setOnItemClickListener(this);
	   
		listView.setOnItemLongClickListener(this);
		top_btn_right.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
			Intent intent = new Intent(HomeActivity.this,WeiBoAddActivity.class);
				intent.putExtra("tip", "记住生命中此刻的痕迹");

				startActivity(intent);
			}
		});
//		tv_msg.setOnClickListener(new OnClickListener() {
//			
//			public void onClick(View v) {
//				//Toast.makeText(HomeActivity.this, "我将消失了", Toast.LENGTH_SHORT).show();
//				executorService.submit(new GetHomeTimeLineThread());
//				tv_msg.setVisibility(View.GONE);//隐藏更多提示的TextView
//				loading.setVisibility(View.VISIBLE);//显示最下方的进度条
//			}
//		});
	}
	
	 public void initFootView()
	    {
	    	LinearLayout layout = new LinearLayout(this);
	        // 设置布局 水平方向
	        layout.setOrientation(LinearLayout.HORIZONTAL);
	        progressBar = new ProgressBar(this);
	        progressBar.setPadding(0, 0, 15, 0);  // 进度条显示位置
	        layout.addView(progressBar, mLayoutParams);
	        TextView textView = new TextView(this);
	        textView.setText("加载中...");
	        textView.setGravity(Gravity.CENTER_VERTICAL);
	        layout.addView(textView, FFlayoutParams);       
	        layout.setGravity(Gravity.CENTER); // 设置layout的重力方向，即对齐方式是
	        loadingLayout = new LinearLayout(this);   // 设置ListView的页脚layout
	        loadingLayout.addView(layout, mLayoutParams);
	        loadingLayout.setGravity(Gravity.CENTER);
	        
	        listView.addFooterView(loadingLayout);
	        

	    	
	    }
	
	
	class GetHomeTimeLineHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			System.out.println("xxxxxxxxxx处理线程后的 handlerxxxxxxx");
			
			adapter = new HomeAdapter(HomeActivity.this, list);
			
			
			System.out.println("GetHomeTimeLineHandler:"+"测试list：list(0)="+list.get(0).toString());
//			if(TOTAL_PAGE>1){
//				adapter.notifyDataSetChanged();
//			}
//			if(TOTAL_PAGE==1){
			listView.setAdapter(adapter);
			//adapter.notifyDataSetChanged();
		//	}
			listView.setSelection((TOTAL_PAGE-1)*PAGE_SIZE+1);//(TOTAL_PAGE-1)*PAGE_SIZE+1);//设置最新获取一页数据成功后显示数据的起始数据
			progressDialog.dismiss();// 关闭进度条
		//	loading.setVisibility(View.GONE);//隐藏下方的进度条
		//	tv_msg.setVisibility(View.VISIBLE);//显示出更多提示TextView
			
			
		
		}
	}
	
	
	
	
	class GetHomeTimeLineThread implements Runnable{
		@Override
		public void run() {
		
			System.out.println("d第二个线程 发送消息");
			
			refreshList();
			Message msg = handler.obtainMessage(123);//通知线程来处理范围的数据
			handler.sendMessage(msg);		
	
		
		}
	}
	
	private void refreshList(){
     	String json=client.getHomeMsg(PageType.PageFist,(TOTAL_PAGE+1)*PAGE_SIZE);
		//array=JSONArray.fromObject(json);		
     	try {
			array=new JSONArray(json);
		 	
			System.out.println("array===="+array);
			if(array!=null&&array.length()>0)
			{
				TOTAL_PAGE++;
				list.clear();
				int lenth =array.length();
				
				for(int i = 0;i<lenth;i++){
					
					list.add(array.getJSONObject(i));
					System.out.println("   refreshList===="+list.get(i));
				}
			}
			else
			{
				System.out.println("in refresh array 为空");
			}
	
    	} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	class HomeAdapter extends BaseAdapter {
		private Context context;
		private LayoutInflater inflater;
		private List<JSONObject> list;
		
		public HomeAdapter(Context context, List<JSONObject> list) {
			super();
			this.context = context;
			this.list = list;
			this.inflater = LayoutInflater.from(context);
			
		
		}

		
		public int getCount() {
			return list.size();
		}

		
		public Object getItem(int position) {
			return list.get(position);
		}

		
		public long getItemId(int position) {
			return position;
		}

		
		public View getView(final int position, View convertView, ViewGroup parent) {
			asyncImageLoader = new AsyncImageLoader();
			HomeViewHolder viewHolder = new HomeViewHolder(); 
			JSONObject data = (JSONObject)list.get(position);
		
			convertView = inflater.inflate(R.layout.home_list_item, null);
			
			viewHolder.home_headicon = (ImageView) convertView.findViewById(R.id.headicon);
			viewHolder.home_nick = (TextView) convertView.findViewById(R.id.nickname);
			viewHolder.home_content = (TextView) convertView.findViewById(R.id.content);			
			viewHolder.home_timestamp = (TextView) convertView.findViewById(R.id.timestamp);
			/****************************************************************************************************************************************************/
			/*                                                                                       有了数据后改称后面的                                                                             */
			/****************************************************************************************************************************************************/
			String mess_id="mess_id";//data.get("mess_id")
			String user_name="myboy";//data.getString("user_name")
			String mess_time="2010-11-09";    //data.getString("mess_time");
			String headicon1="https://www.google.com.hk/images/nav_logo107.png" ; //String headiconurl1=data.getString("headicon");
			String mess_content = "孙子 我是你爷爷";//data.getString("mess_content")
			if(data!=null)
			{					
					 try {
						mess_id=data.getString("mess_id");				
						user_name=data.getString("user_name");
						mess_time=data.getString("mess_time");
						headicon1=data.getString("headicon");
						mess_content = data.getString("mess_content");
					 
					 	} catch (JSONException e) {
						
							e.printStackTrace();
						}
				
					
				
					
			}
			//异步加载图片
			//headicon1=headicon1.replace('\', '');
			System.out.println("******************************headicon1="+headicon1);
			Drawable cachedImage = asyncImageLoader.loadDrawable(headicon1,viewHolder.home_headicon, new ImageCallback(){				    
		    public void imageLoaded(Drawable imageDrawable,ImageView imageView, String imageUrl) {
		        imageView.setImageDrawable(imageDrawable);
		    }
	     	});
					convertView.setTag(mess_id);		
					
					viewHolder.home_nick.setText(user_name);
					viewHolder.home_timestamp.setText(TimeUtil.converTime(mess_time));
					
					viewHolder.home_content.setText(mess_content);
						
						
				if (cachedImage == null) 
					viewHolder.home_headicon.setImageResource(R.drawable.icon);
				 else 
					viewHolder.home_headicon.setImageDrawable(cachedImage);		
					
			
		


			return convertView;
	}
	}
	
	
	
	static  class HomeViewHolder {
		private ImageView home_headicon;
		private TextView home_nick;		
		private TextView home_timestamp;
		private TextView home_content;		
		
	}

	
	public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
//		CharSequence [] items = null;
//		try {
//			items= new CharSequence[]{"转播","对话","点评","收藏",((JSONObject)array.opt(position)).getString("nick"),"取消"};
//		} catch (JSONException e) {
//			e.printStackTrace();
//		}
//		new AlertDialog.Builder(HomeActivity.this).setTitle("选项").setItems(items,new DialogInterface.OnClickListener() {
//			
//			public void onClick(DialogInterface dialog, int which) {
//						switch (which) {
//						case 0: {
//						}
//							break;
//						case 1: {
//						}
//							break;
//						case 2: 
//						default:
//							break;
//						}
//			}
//		}).show();
		return false;
	}

	
	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		Toast.makeText(this, "item click", 1).show();

		
		JSONObject weiboInfo = (JSONObject)array.opt(position);
	//	Intent intent = new Intent(this, WeiBoDetailActivity.class);		// this 改为 this.parent()也试过了 还是直接挂掉了
		//Bundle bundle=new Bundle();
		//bundle.putString("weiboid", weiboInfo.toString());
		//intent.putExtras(bundle);
		jumptoActivity(WeiBoDetailActivity.class,"WeiBoDetailActivity",new String[]{"weiboid"},new String[]{weiboInfo.toString()});
	//Window w=WeiBoGroupTab.group.getLocalActivityManager().startActivity("DetailActivity", intent);
	//	WeiBoGroupTab.group.setContentView(w.getDecorView());
//		
//		Toast.makeText(this,this.getParent().getPackageName()+"就是这个是HomeAct的parent" +
//				"", 1).show();
	
		//startActivity(intent);
		//HomeActivity.this.finish();
		
}
	private void jumptoActivity(Class activity,String activityname ,String key[],String value[]){
		Intent intent = new Intent(HomeActivity.this, activity);  
		if(key!=null&&value!=null&&key.length==value.length)
		
			for(int i=0;i<key.length;++i)
				intent.putExtra(key[i], value[i]);
        // 把Activity转换成一个Window，然后转换成View  
        Window w = FourthGroupTab.group.getLocalActivityManager()  
                .startActivity(activityname,intent);  
        View view = w.getDecorView();  
        //设置要跳转的Activity显示为本ActivityGroup的内容  
        FourthGroupTab.group.setContentView(view); 
	}

	public boolean onCreateOptionsMenu(Menu menu){
		//super.onCreateOptionsMenu(menu);
		MenuInflater menuInflater = getMenuInflater();
		//menuInflater.inflate(R.menu.home_timeline_menu, menu);                 //有必要的时候再加上去
		return true;
	}
	
	
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
//
	      }
		return false;
		}

	@Override
	public void finish() {
		// TODO Auto-generated method stub
		
		executorService.shutdown();
		//this.finish();
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		// TODO Auto-generated method stub
		
		if(firstVisibleItem+visibleItemCount==totalItemCount)
		{
//			if(mThread==null||!mThread.isAlive())
//			{
//				mThread=new Thread()
//				{	@Override
//					public void run() {
//						super.run();
//						try {
//							 
//							//这里放网络数据请求的方法，我在这里用线程休眠5秒方法来处理
//							Thread.sleep(5000);
//							String json=TEST_WeiBoAPI_GetSFromNetWork();//测试数据
//							
//							
//						} catch (InterruptedException e) {
//							// TODO Auto-generated catch block
//							e.printStackTrace();
//						}
					
						executorService.submit(new GetHomeTimeLineThread()); //得到新数据
						Message message=new Message();
						message.what=1;
						loadinghandler.sendMessage(message);						
					}

//			
//					
//				};
//				mThread.start();
			
			
		
	}

	@Override
	public void onScrollStateChanged(AbsListView arg0, int arg1) {
		// TODO Auto-generated method stub
		
		
		
	}
	


}



	

